<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { logger } from '../utils/logger'
import { wsManager } from '../utils/websocket'

// 路由
const router = useRouter()

// 右键菜单显示状态
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })
const currentDataset = ref(null)

// 筛选弹窗显示状态
const filterDialogVisible = ref(false)
const isAutoFiltering = ref(false)
const autoFilterProgress = ref(0)
const allFiles = ref([])
const filteredFiles = ref([])

// 数据集详情弹窗显示状态
const detailDialogVisible = ref(false)
const datasetFiles = ref([])

// 数据集列表
const datasets = ref([])

// 更新时间函数
const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 按钮状态
const buttonStates = ref({
  home: '正常',
  user: '正常',
  dataImport: '正常',
  dataManage: 'normal',
  dataAnnotation: 'normal'
})

// 获取当前时间
const currentTime = ref('')

// WebSocket连接状态
const wsConnected = ref(false)

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    if (!wsManager.ws || wsManager.ws.readyState !== WebSocket.OPEN) {
      await wsManager.connect()
    }
    wsConnected.value = true
  } catch (error) {
    console.error('WebSocket连接失败:', error)
  }
}

onMounted(() => {
  document.addEventListener('click', handleDocumentClick)
  initWebSocket()
  
  // 添加WebSocket消息监听
  const messageHandler = (event) => {
    const response = JSON.parse(event.data)
    if (response.operation === 'dataheartbeat') {
      // 转换数据格式
      datasets.value = response.params.map(item => ({
        datasetId: item.id,
        name: item.id,
        status: item.status,
        progress: item.progress,
        lastModified: item.last_modified,
        size: item.size,
        attribute: item.attribute
      }))
      
      // 检查当前数据集ID是否匹配
      if (currentDataset.value && filterDialogVisible.value) {
        const matchedDataset = response.params.find(item => item.id === currentDataset.value.datasetId)
        if (matchedDataset && matchedDataset.status === 'autofiltering') {
          autoFilterProgress.value = matchedDataset.progress
        }
      }
    }
  }
  
  wsManager.ws.addEventListener('message', messageHandler)
  
  // 保存handler引用以便卸载时移除
  window._currentMessageHandler = messageHandler
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick)
  // 移除WebSocket消息监听
  if (wsManager.ws && window._currentMessageHandler) {
    wsManager.ws.removeEventListener('message', window._currentMessageHandler)
    delete window._currentMessageHandler
  }
})
onMounted(() => {
  // 更新时间
  updateTime()
  setInterval(updateTime, 1000)
})

// 在setup函数中添加
const handleDocumentClick = (event) => {
  if (contextMenuVisible.value && !event.target.closest('.context-menu')) {
    contextMenuVisible.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleDocumentClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick)
})

// 获取状态图标路径
const getStatusIcon = (status) => {
  switch(status) {
    case 'imported':
      return '/pic/dataManagement/未处理.png'
    case 'formated':
      return '/pic/dataManagement/已格式化.png'
    case 'autofiltered':
      return '/pic/dataManagement/已完成筛选.png'
    default:
      return '/pic/dataManagement/未处理.png'
  }
}

// 显示右键菜单
const showContextMenu = (event, dataset) => {
  event.preventDefault()
  currentDataset.value = dataset
  contextMenuPosition.value = { x: event.clientX, y: event.clientY }
  contextMenuVisible.value = true
}

const formatDataset = async () => {
  try {
    const response = await wsManager.sendMessage({
      requestID: Date.now().toString(),
      operation: 'format',
      uid: localStorage.getItem('username') || '',
      params: { id: currentDataset.value.datasetId },
      authToken: localStorage.getItem('authToken') || ''
    }); 
    
    if (response.status === 1) {
      ElMessage.success('格式化请求已发送');
    } else {
      ElMessage.error('格式化请求失败');
    }
  } catch (error) {
    console.error('格式化请求出错:', error);
    ElMessage.error('格式化请求出错');
  }
};

const startFilter = async () => {
  allFiles.value = [];
  filteredFiles.value = [];
  try {
    const response = await wsManager.sendMessage({
      requestID: Date.now().toString(),
      operation: 'filter',
      uid: localStorage.getItem('username') || '',
      params: { id: currentDataset.value.datasetId },
      authToken: localStorage.getItem('authToken') || ''
    });
    currentDataset.value.status = 'autofiltering';
    console.log("response", response)

    if (response.status === 1) {
      allFiles.value = response.params;
      filterDialogVisible.value = true;
      ElMessage.success('筛选请求已发送');
    } else {
      ElMessage.error('筛选请求失败');
    }
  } catch (error) {
    console.error('筛选请求出错:', error);
    ElMessage.error('筛选请求出错');
  }
};

const viewOriginalData = async () => {
  try {
    const response = await wsManager.send({
      requestID: Date.now().toString(),
      operation: 'filter',
      uid: 'user-id',
      params: { id: currentDataset.value.datasetId },
      authToken: 'token'
    });
    
    if (response.status === 1) {
      allFiles.value = response.params;
      filterDialogVisible.value = true;
      ElMessage.success('筛选请求已发送');
    } else {
      ElMessage.error('筛选请求失败');
    }
  } catch (error) {
    console.error('筛选请求出错:', error);
    ElMessage.error('筛选请求出错');
  }
};

const moveAllSelectedToFiltered = () => {
  const selectedFiles = allFiles.value.filter(file => file.selected);
  filteredFiles.value = [...filteredFiles.value, ...selectedFiles];
  allFiles.value = allFiles.value.filter(file => !file.selected);
};

const moveAllSelectedToUnfiltered = () => {
  const selectedFiles = filteredFiles.value.filter(file => file.selected);
  allFiles.value = [...allFiles.value, ...selectedFiles];
  filteredFiles.value = filteredFiles.value.filter(file => !file.selected);
};

const toggleFileSelection = (file, list) => {
  file.selected = !file.selected;
};

const startAutoFilter = async () => {
  try {
    isAutoFiltering.value = true;
    const requestData = {
      requestID: Date.now().toString(),
      operation: 'autofilter',
      uid: localStorage.getItem('username') || '',
      params: { id: currentDataset.value.datasetId },
      authToken: localStorage.getItem('authToken') || ''
    }
    console.log("requestData", requestData);
    const response = await wsManager.sendMessage(requestData);
    console.log("response", response)
    // alert(response.status)
    if (response.status === 1) {
      console.log("自动筛选完成", "自动筛选完成")
      allFiles.value = response.params.unfiltered;
      filteredFiles.value = response.params.filtered;
      ElMessage.success('自动筛选完成');
    } else {
      ElMessage.error('自动筛选失败');
    }
  } catch (error) {
    console.error('自动筛选出错:', error);
    ElMessage.error('自动筛选出错');
  } finally {
    isAutoFiltering.value = false;
  }
};

const confirmFilter = async () => {
  try {
    const requestData = {
      requestID: Date.now().toString(),
      operation: 'filtered',
      uid: localStorage.getItem('username') || '',
      params: {
        packageid: currentDataset.value.datasetId,
        unfiltered: allFiles.value,
        filtered: filteredFiles.value
      },
      authToken: localStorage.getItem('authToken') || ''
    }
    const response = await wsManager.sendMessage(requestData);
    console.log("requestData", requestData)
    console.log("response", response)
    if (response.status === 1) {
      alert(1)
      ElMessage.success('筛选结果已保存');
      filterDialogVisible.value = false;
    } else {
      ElMessage.error('筛选结果保存失败');
    }
  } catch (error) {
    console.error('筛选结果保存出错:', error);
    ElMessage.error('筛选结果保存出错');
  } finally {
    filterDialogVisible.value = false;
  }
}

// 返回主页
const goToHome = () => {
  router.push('/')
}

const goToDataManagement = () => {
  router.push('/data-management')
} 

const goToDataAnnotation = () => {
  router.push('/data-annotation')
}

// 鼠标事件处理
const handleMouseEnter = (button) => {
  buttonStates.value[button] = '悬浮'
}

const handleMouseLeave = (button) => {
  buttonStates.value[button] = '正常'
}

const handleMouseDown = (button) => {
  buttonStates.value[button] = '点击'
}

const handleMouseUp = (button) => {
  buttonStates.value[button] = '悬浮'
}
</script>

<template>
  <div class="data-management">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <img src="/pic/dataManagement/logo-菜单左上方位置.png" alt="Logo">
      </div>
      <div class="nav-buttons">
        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataManage')"
             @mouseleave="handleMouseLeave('dataManage')"
             @mousedown="handleMouseDown('dataManage')"
             @mouseup="handleMouseUp('dataManage'); goToDataManagement()">
          <img :src="`/pic/dataManagement/数据管理-${buttonStates.dataManage === 'normal' ? '正常' : '悬浮'}.png`" alt="数据管理">
        </div>

        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataAnnotation')"
             @mouseleave="handleMouseLeave('dataAnnotation')"
             @mousedown="handleMouseDown('dataAnnotation')"
             @mouseup="handleMouseUp('dataAnnotation'); goToDataAnnotation()">
          <img :src="`/pic/dataManagement/数据标注-${buttonStates.dataAnnotation === 'normal' ? '正常' : '悬浮'}.png`" alt="数据标注">
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部栏 -->
      <div class="top-bar">
        <div class="system-name">算筹平台系统</div>
        <div class="home-button"
             @mouseenter="handleMouseEnter('home')"
             @mouseleave="handleMouseLeave('home')"
             @mousedown="handleMouseDown('home')"
             @mouseup="handleMouseUp('home')"
             @click="goToHome">
          <img :src="`/pic/dataManagement/首页-${buttonStates.home}.png`" alt="首页">
        </div>
        <div class="current-time">{{ currentTime }}</div>
        <div class="user-info">
          <div class="user-button"
               @mouseenter="handleMouseEnter('user')"
               @mouseleave="handleMouseLeave('user')"
               @mousedown="handleMouseDown('user')"
               @mouseup="handleMouseUp('user')">
            <img :src="`/pic/dataManagement/用户-${buttonStates.user}.png`" alt="用户">
          </div>
          <span class="username">用户：XXXX</span>
        </div>
      </div>

      <!-- 数据集管理区域 -->
      <div class="dataset-management">
        <!-- 数据导入按钮 -->
        <div class="data-import-button"
             @mouseenter="handleMouseEnter('dataImport')"
             @mouseleave="handleMouseLeave('dataImport')"
             @mousedown="handleMouseDown('dataImport')"
             @mouseup="handleMouseUp('dataImport')"
             @click="openFileSelector">
          <img :src="`/pic/dataManagement/数据导入-${buttonStates.dataImport}.png`" alt="数据导入">
        </div>

        <!-- 状态图标说明 -->
        <div class="status-legend">
          <div class="legend-item">
            <img src="/pic/dataManagement/未处理.png" alt="未处理">
            <span>未处理</span>
          </div>
          <div class="legend-item">
            <img src="/pic/dataManagement/已格式化.png" alt="已格式化">
            <span>已格式化</span>
          </div>
          <div class="legend-item">
            <img src="/pic/dataManagement/已完成筛选.png" alt="已完成筛选">
            <span>已完成筛选</span>
          </div>
        </div>

        <!-- 数据集列表 -->
        <div class="dataset-list">
          <div v-for="dataset in datasets" :key="dataset.datasetId" class="dataset-card"
               @contextmenu="showContextMenu($event, dataset)">
            <div class="dataset-image">
              <img src="/pic/dataManagement/数据集.png" alt="数据集">
              <img :src="getStatusIcon(dataset.status)" alt="状态" class="status-icon">
            </div>
            <div class="dataset-info">
              <div class="dataset-name">{{ dataset.name }}</div>
              <div class="progress-bar">
                <div class="progress" :style="{ width: dataset.progress + '%' }"></div>
              </div>
              <div class="progress-text">{{ dataset.progress }}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

    <!-- 右键菜单 -->
    <div v-if="contextMenuVisible" class="context-menu" :style="{ top: contextMenuPosition.y + 'px', left: contextMenuPosition.x + 'px' }">
      <div class="context-menu-item" @click="formatDataset" :class="{ 'disabled': currentDataset?.status !== 'imported' }">格式化</div>
      <div class="context-menu-item" @click="startFilter" :class="{ 'disabled': currentDataset?.status !== 'formated' }">开始筛选</div>
      <div class="context-menu-item" @click="viewOriginalData" :class="{ 'disabled': ['importing', 'formating', 'autofiltering'].includes(currentDataset?.status) }">查看原始数据</div>
    </div>
    
    <!-- 隐藏的文件输入 -->
    <input 
      ref="fileInputRef" 
      type="file" 
      multiple 
      accept="image/*,video/*,audio/*" 
      style="display: none;" 
      @change="handleFileSelect"
    />
    
    <!-- 数据筛选弹窗 -->
    <div v-if="filterDialogVisible" class="filter-dialog">
      <div class="filter-dialog-header">
        <span>数据筛选</span>
        <button class="close-button" @click="filterDialogVisible = false">×</button>
      </div>
      
      <div class="auto-filter-section">
        <button class="auto-filter-button" @click="startAutoFilter" :disabled="isAutoFiltering">自动筛选</button>
        <div class="progress-bar-container">
          <div class="progress-bar">
            <div class="progress" :style="{ width: autoFilterProgress + '%' }"></div>
          </div>
          <span class="progress-text">{{ autoFilterProgress }}%</span>
        </div>
      </div>
      
      <div class="transfer-container">
        <div class="transfer-panel">
          <div class="panel-header">未筛选文件</div>
          <div class="file-list">
            <div v-for="file in allFiles" :key="file.name" class="file-item" :class="{ 'selected': file.selected }" @click="toggleFileSelection(file, allFiles)">
              <img :src="file.thumb" alt="缩略图">
              <div class="file-name">{{ file.name }}</div>
            </div>
          </div>
        </div>
        
        <div class="transfer-buttons">
          <button @click="moveAllSelectedToFiltered">》</button>
          <button @click="moveAllSelectedToUnfiltered">《</button>
        </div>
        
        <div class="transfer-panel">
          <div class="panel-header">已筛选文件</div>
          <div class="file-list">
            <div v-for="file in filteredFiles" :key="file.name" class="file-item" :class="{ 'selected': file.selected }" @click="toggleFileSelection(file, filteredFiles)">
              <img :src="file.thumb" alt="缩略图">
              <div class="file-name">{{ file.name }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="filter-dialog-footer">
        <button class="cancel-button" @click="cancelFilter">取消</button>
        <button class="confirm-button" @click="confirmFilter">确定</button>
      </div>
    </div>
    
    <!-- 数据集详情弹窗 -->
    <div v-if="detailDialogVisible" class="detail-dialog">
      <div class="detail-dialog-header">
        <span>数据集详情</span>
        <button class="close-button" @click="detailDialogVisible = false">×</button>
      </div>
      
      <div class="detail-content">
        <div v-for="file in datasetFiles" :key="file.name" class="detail-file-item">
          <img :src="file.thumb" alt="缩略图">
          <div class="file-name">{{ file.name }}</div>
        </div>
      </div>
    </div>
</template>

<style scoped>
.data-management {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.sidebar {
  width: 0px;
  background-color: #4a6baf;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.logo img {
  width: 60px;
  height: auto;
}

.nav-buttons {
  margin-top: 20px;
}

.nav-button {
  margin-bottom: 10px;
  cursor: pointer;
}

.nav-button img {
  width: 60px;
  height: auto;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.top-bar {
  height: 60px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 10px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.system-name {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.home-button {
  margin-left: 20px;
  cursor: pointer;
}

.current-time {
  margin-left: auto;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.user-button {
  cursor: pointer;
  margin-right: 10px;
}

.username {
  color: #333;
}

.dataset-management {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}

.data-import-button {
  margin-bottom: 20px;
  cursor: pointer;
}

.status-legend {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-item img {
  width: 20px;
  height: 20px;
}

.dataset-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.dataset-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dataset-image {
  position: relative;
  width: 100%;
  padding-top: 100%;
}

.dataset-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.status-icon {
  position: absolute;
  bottom: 10px;
  left: 10px;
  width: 24px !important;
  height: 24px !important;
}

.dataset-info {
  padding: 10px;
}

.dataset-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
}

.progress-bar {
  height: 4px;
  background-color: #e0e0e0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress {
  height: 100%;
  background-color: #4a6baf;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  text-align: right;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  min-width: 120px;
}

.context-menu-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.context-menu-item:hover {
  background-color: #f0f2f5;
}

.context-menu-item.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.context-menu-item.disabled:hover {
  background-color: transparent;
}

/* 筛选弹窗样式 */
.filter-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  width: 800px;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}

.filter-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #4a6baf;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.close-button {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
}

.auto-filter-section {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.auto-filter-button {
  background-color: #4a6baf;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.auto-filter-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.progress-bar-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #4a6baf;
  transition: width 0.3s ease;
}

.transfer-container {
  display: flex;
  padding: 0 16px 16px;
  gap: 16px;
  flex: 1;
  min-height: 300px;
  overflow: hidden;
}

.transfer-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.panel-header {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-weight: bold;
}

.file-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
}

.file-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.2s;
}

.file-item.selected {
  border-color: #4a6baf;
  background-color: rgba(74, 107, 175, 0.1);
}

.file-item img {
  width: 100%;
  height: 80px;
  object-fit: cover;
}

.file-name {
  padding: 4px;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
}

.transfer-buttons button {
  background-color: #4a6baf;
  color: white;
  border: none;
  width: 30px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
}

.filter-dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  gap: 12px;
  border-top: 1px solid #e0e0e0;
}

.cancel-button, .confirm-button {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button {
  background-color: white;
  border: 1px solid #d9d9d9;
  color: #333;
}

.confirm-button {
  background-color: #4a6baf;
  border: none;
  color: white;
}

/* 数据集详情弹窗样式 */
.detail-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  width: 800px;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.detail-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #4a6baf;
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.detail-content {
  padding: 16px;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  max-height: 70vh;
}

.detail-file-item {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.detail-file-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}
</style>